#!usr/bin/env python  
# -*- coding:utf-8 _*-
""" 
@author:robot
@file: tmf_task_ws.py 
@version:
@time: 2022/06/15 
"""
import websockets
import asyncio
import json

log_data = ''


def build_log_body(sub_task_id):
    return {
        "type": "logs",
        "filter": {
            "where": {
                "contextMap.dataFlowId": {
                    "eq": f'{sub_task_id}'
                }
            },
            "order": "id DESC",
            "limit": 100,
            'skip': 0
        }
    }


async def get_log(ws_uri, ws_body):
    async with websockets.connect(ws_uri) as ws:
        await ws.send(json.dumps(ws_body))
        while True:
            response = json.loads(await ws.recv())
            if response is None:
                continue
            else:
                global log_data
                log_data = response
            await ws.close()


def ws_get_log(ws_uri, sub_task_id):
    ws_body = build_log_body(sub_task_id)
    global log_data
    try:
        asyncio.get_event_loop().run_until_complete(get_log(ws_uri, ws_body))
    except Exception as e:
        assert str(e) == "code = 1000 (OK), no reason"
    return log_data
